package com.pearlsoft.webapp.core.dataset;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pearlsoft.commons.utils.JsonUtil;
import com.pearlsoft.webapp.core.dataset.AbstractDataSet;
import com.pearlsoft.webapp.core.dataset.Condition;
import com.pearlsoft.webapp.core.dataset.DataSetException;
import com.pearlsoft.webapp.core.dataset.DataSetFilter;
import com.pearlsoft.webapp.core.dataset.Field;

/**
 * 
 * ListDataSet
 * 
 * @Creator haitingr
 * @Create-DateTime 2011-10-24
 */
public class DefaultDataSet extends AbstractDataSet {

	public DefaultDataSet(String name) {
		super(name);
	}

	public DefaultDataSet(String name, List<Field> fields, List<DataSetFilter> filters) {
		super(name, fields, filters);
	}

	public DefaultDataSet(String name, List<Field> fields) {
		super(name, fields);
	}

	public byte[] toJson() throws IOException, DataSetException {
		Map<String, Object> values = new HashMap<String, Object>();
		values.put(_name_attribute, name);

		Map<String, Object> pages = new HashMap<String, Object>();

		pages.put("start", this.getStartIndex());
		pages.put("total", this.getTotalCount());
		pages.put("pagesize", this.getPageSize());

		values.put(_page_attribute, pages);
		values.put(_sucess_attribute,this.isSuccess());
		List<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
		this.reset();
		while (this.next()) {
			records.add(this.currentRecord.toMap());
		}
		this.reset();
		values.put(_record_attriubte, records);

		Map<String, Object> conditions = new HashMap<String, Object>();
		for (Condition condition : this.conditions) {
			conditions.put(condition.getFieldName(), condition.getValue());
		}
		values.put(_condition_attribute, conditions);

		List<Map<String, Object>> fields = new ArrayList<Map<String, Object>>();
		for (Field f : this.fields.values()) {
			fields.add(f.toMap());
		}
		values.put(_field_attribute, fields);

		return JsonUtil.toJson(values);
	}

	public static void main(String[] args) throws Exception {
	}



}
